/*
 * To change this template, chooser Tools | Templates
 * and open the template in the editor.
 */

package amd.core;

import amd.core.data.ListDocWeight;
import amd.core.extraction.DocExtractor;
import amd.core.search.SearchDocRelevant;
import amd.core.search.SearchDocSimilar;
import amd.database.ConnectDB;
import amd.database.QueryNoResultException;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Properties;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileFilter;

/**
 *
 * @author Latifah Dwi Nurachma
 */
public class UIListener {
    private File currentDir;
    private JFrame frame;
    private FileFilter fileFilter;
    private String targetPath;
    private String sourcePath;
    private String textEditorPath;
    private String pdfReaderPath;
    private ConnectDB conn;
    private String logFile;
    private float treshold;

    private Properties properties;
    //private FrameMenuUpload menuUpload;
    
    public UIListener(JFrame frame) throws Exception{
        logFile = "log.txt";
        PrintStream errp=null;
        errp = new PrintStream(new FileOutputStream(logFile, true));
        System.setOut(errp);

        properties = LoadXmlProperties.readProperties("config.xml");

        conn = new ConnectDB(properties.getProperty("database.url"),
                properties.getProperty("database.username"),
                properties.getProperty("database.password"));

        sourcePath = properties.getProperty("folder.source");
        if(!new File(sourcePath).exists()){
            new File(sourcePath);
        }
        targetPath = properties.getProperty("folder.target");
        if(!new File(targetPath).exists()){
            new File(targetPath);
        }

        textEditorPath = properties.getProperty("program.texteditor","C:\\WINDOWS\\system32\\notepad.exe");
        pdfReaderPath = properties.getProperty("program.pdfreader");
        treshold = Float.valueOf(properties.getProperty("treshold"));

        currentDir = new File(".");
        this.frame = frame;
        fileFilter = new FileFilter() {
            @Override
            public boolean accept(File f) {
                return (f.isDirectory() || f.getName().endsWith(".pdf"));
            }
            @Override
            public String getDescription() {
                return "PDF Files";
            }
        };

    }


    public  void ekstrakDokumen() {
        DocExtractor.extractAllDocument(conn, new File(sourcePath), new File(targetPath));
        JOptionPane.showMessageDialog(frame, "Dokumen telah selesai diekstrak","Berhasil",JOptionPane.INFORMATION_MESSAGE,null);
    }

    public void login() {

    }

    public void searchDocumentByKeyword(String inputKeyword){
        try {
            ListDocWeight foundDocument = SearchDocRelevant.search(conn, inputKeyword);
            if(!foundDocument.isEmpty()){
                int i = 0;
                //String s = "Mencari dokumen berdasarkan keyword \"" + inputKeyword + "\"\n";
                String s = "";
                
                while (i < foundDocument.size()) {
                    s = s + "---Dokumen ke-" + (i + 1) + " adalah " + foundDocument.get(i).getIdDoc() + " dengan bobot " + foundDocument.get(i).getWeight() + "\n";
                    i++;
                }
                JOptionPane.showMessageDialog(frame,
                        s ,"Dokumen ditemukan", JOptionPane.INFORMATION_MESSAGE, null);
            }
            else{
                JOptionPane.showMessageDialog(frame,
                    "Tidak ditemukan dokumen yang mengandung keyword \'" + inputKeyword +"\'",
                    "Dokumen tidak ditemukan", JOptionPane.INFORMATION_MESSAGE, null);
            }

        } catch (QueryNoResultException ex) {
            
        }
    }

    public ArrayList<ArrayList<String>> searchDocumentByKeyword(String inputKeyword, int page){
        ArrayList<ArrayList<String>> listDoc = new ArrayList<ArrayList<String>>();
        try {
            listDoc = SearchDocRelevant.search(conn, inputKeyword, treshold, page);
        } catch (QueryNoResultException ex) {
                JOptionPane.showMessageDialog(frame,
                    "Tidak ditemukan dokumen yang mengandung keyword \'" + inputKeyword +"\'",
                    "Dokumen tidak ditemukan", JOptionPane.INFORMATION_MESSAGE, null);
        }
        return listDoc;
    }

    public void searchDocumentSimilar(String idDocReff){
        try {
            ArrayList<ArrayList<String>> docSimilar = SearchDocSimilar.search(conn, idDocReff);
//            if (!docSimilar.isEmpty()) {
//                int i = 0;
//                System.out.println("Dokumen yang similar dengan \'" + idDocReff + "\' adalah:");
//                while (i < docSimilar.size()) {
//                    System.out.println(docSimilar.get(i).getIdDoc() + "\t" + docSimilar.get(i).getWeight());
//                    i++;
//                }
//            }
        } catch (QueryNoResultException ex) {

        }
    }


    public void searchDocumentSimilar(String idDocReff, int page){
        try {
            ArrayList<ArrayList<String>> docSimilar = SearchDocSimilar.search(conn, idDocReff, 0, page);
//            if (!docSimilar.isEmpty()) {
//                int i = 0;
//                System.out.println("Dokumen yang similar dengan \'" + idDocReff + "\' adalah:");
//                while (i < docSimilar.size()) {
//                    System.out.println(docSimilar.get(i).getIdDoc() + "\t" + docSimilar.get(i).getWeight());
//                    i++;
//                }
//            }
        } catch (QueryNoResultException ex) {

        }
    }

    public void uploadDocument(){
        JFileChooser chooser = new JFileChooser();
        chooser.setCurrentDirectory(currentDir);
        chooser.setFileFilter(fileFilter);
        chooser.setAcceptAllFileFilterUsed(false);
        int result = chooser.showOpenDialog(frame);
        if (result == JFileChooser.APPROVE_OPTION) {
            File file = chooser.getSelectedFile();
            String name = chooser.getSelectedFile().getPath();
            currentDir = new File(name).getParentFile();
            if(file.getName().endsWith(".pdf")){
                try {
                    FileOperations.copyFilePdf(name, sourcePath);
                    JOptionPane.showMessageDialog(frame, "File " + file.getName() + " telah berhasil di upload.", "Berhasil", JOptionPane.INFORMATION_MESSAGE, null);
                    System.out.println(CurrentDateAndTime.getDateTime() + " Upload dokumen dari " + file.getPath() + " ke "+ sourcePath +" berhasil.");

                } catch (Exception ex) {
                    JOptionPane.showMessageDialog(frame,
                            "Dokumen gagal di-upload\n"+ex.getMessage(),
                            "Gagal", JOptionPane.INFORMATION_MESSAGE, null);
                }
            }
            else{
                //message box bahwa dia mengupload file bukan pdf
                JOptionPane.showMessageDialog(frame, "File "+ file.getName() + " tidak berformat PDF.\nFile tidak berhasil diupload.","Gagal",JOptionPane.WARNING_MESSAGE,null);
            }
        }
    }

    public String browseDocument() {
        JFileChooser chooser = new JFileChooser();
        chooser.setCurrentDirectory(currentDir);
        chooser.setFileFilter(fileFilter);
        chooser.setAcceptAllFileFilterUsed(false);
        int result = chooser.showOpenDialog(frame);
        String fileName = "";
        if (result == JFileChooser.APPROVE_OPTION) {
            File file = chooser.getSelectedFile();
            String name = chooser.getSelectedFile().getPath();
            currentDir = new File(name).getParentFile();
            if(file.getName().endsWith(".pdf")){
                fileName = file.getPath();
            }
            else{
                //message box bahwa dia mengupload file bukan pdf
                JOptionPane.showMessageDialog(frame, "File "+ file.getName() + " tidak berformat PDF.\nFile tidak berhasil diupload.","Gagal",JOptionPane.WARNING_MESSAGE,null);
            }
        }
        return fileName;
    }

    public void openPdfDocument(String docPath){
        try {
            Runtime load = Runtime.getRuntime();
            load.exec(pdfReaderPath + " " + docPath);
        } catch (IOException ex) {
            JOptionPane.showMessageDialog(frame, ex.toString(),"Gagal",JOptionPane.WARNING_MESSAGE,null);
        }

    }

    public void uploadDocument(String docPath) {
        try {
            FileOperations.copyFilePdf(docPath, sourcePath);
            JOptionPane.showMessageDialog(frame, "File " + new File(docPath).getName() + " telah berhasil di upload.", "Berhasil", JOptionPane.INFORMATION_MESSAGE, null);
            System.out.println(CurrentDateAndTime.getDateTime() + " Upload dokumen dari " + docPath + " ke "+ sourcePath +" berhasil.");
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(frame,
                    "Dokumen gagal di-upload\n"+ex.getMessage(),
                    "Gagal", JOptionPane.INFORMATION_MESSAGE, null);
        }
    }

    public void viewLog() {
        try {
            Runtime load = Runtime.getRuntime();
            load.exec(textEditorPath + " " + logFile);
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(frame,
                    "Tidak ditemukan file log\n"+ex.getMessage(),
                    "Gagal", JOptionPane.INFORMATION_MESSAGE, null);
        }
    }

}
